from app.core.base_response import UnicornException
from app.core.db.database import db
from app.core.error.code_total import StatusCode
from app.core.sql_compilations import SQLCompilations
from app.utils.tools import Tools


async def create(model):
    _name = model.name
    status = db.fetch_one(SQLCompilations.Category.CHECK, _name).get("number")
    if status == 0:
        id = Tools.uid()
        db.insert(SQLCompilations.Category.CREATE, id,_name)
    else:
        raise UnicornException(StatusCode.R20001["code"], StatusCode.R20001["msg"])

async def delete_category(id):
    category_info =  db.fetch_one(SQLCompilations.Category.GET_ONE, id)
    if category_info:
        db.delete(SQLCompilations.Category.DEL,id)
    else:
        raise UnicornException(StatusCode.R20006["code"], StatusCode.R20006["msg"])

async def update(_id,model):
    _name = model.name
    if db.fetch_one(SQLCompilations.Category.GET_ONE,_id):
        db.update(SQLCompilations.Category.UPDATE, _name,_id)
    else:
        raise UnicornException(StatusCode.R20006["code"],StatusCode.R20006["msg"])


async def read(id):
    result = db.fetch_one(SQLCompilations.Category.GET_ONE, id)
    if result:
        return result
    else:
        raise UnicornException(StatusCode.R20002["code"], StatusCode.R20002["msg"])

async def read_list():
    category_list = db.fetch_all(SQLCompilations.Category.GET_LIST)
    for item in category_list:
        item['create_time'] = Tools.date_format(item['create_time'])
        item['update_time'] = Tools.date_format(item['update_time']) if item['update_time'] else "暂无"

    return category_list

